package com.taxshare.operation.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.operation.entity.MessageInfoEntity;
import com.taxshare.operation.entity.MessageUsersStateEntity;
import com.taxshare.operation.mapper.MessageInfoMapper;
import com.taxshare.operation.view.vo.MessageInfoVO;
import com.taxshare.operation.view.vo.MessageUsersStateVO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.constant.CommonConstant;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liupp
 * @ClassName: MessageInfoService
 * @Description: (消息信息)
 * @date 2021年1月22日
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class MessageInfoService extends ServiceImpl<MessageInfoMapper, MessageInfoEntity> {

    /**
     * @param @param  codeDetailVO
     * @param @return 参数
     * @return Response<List < MessageTemplateVO>> 返回类型
     * @throws
     * @Title: getDetailInfoList
     * @Description: (分页)
     */
    public Response<IPage<MessageInfoVO>> queryPageList(PageRequest<MessageInfoVO> query) {
        QueryWrapper<MessageInfoEntity> queryWrapper = new QueryWrapper<>();
        String state = query.getInfo().getState().toString();
        if (StringUtils.isNotEmpty(state)) {
            List<String> newsTypes = Arrays.asList(state.split(","));
            queryWrapper.in("state", newsTypes);
        }
        String isdelete = query.getInfo().getIsdelete();
        if (StringUtils.isNotEmpty(isdelete)) {
            queryWrapper.eq("isdelete", isdelete);
        }
        queryWrapper.orderByDesc("create_time");
        IPage<MessageInfoVO> result = PageHelp.siamplePage(this, queryWrapper, query.getPage(), MessageInfoVO.class);
        return Response.success(result);
    }

    /**
     * 新增
     */
    public Response addTemplate(MessageInfoVO pojo) {
        MessageInfoEntity infoBean = DozerBeanUtil.map(pojo, MessageInfoEntity.class);
        infoBean.setUuid(UUIDUitl.UUID32(false));
        infoBean.setCreateTime(new Date());
        infoBean.setUpdateTime(new Date());
        this.save(infoBean);
        return Response.success();
    }

    /**
     * 编辑
     */
    public Response updateTemplate(MessageInfoVO messageInfoVO) {
        MessageInfoEntity infoBean = this.getById(messageInfoVO.getUuid());
        infoBean.setState(messageInfoVO.getState());
        infoBean.setUpdateTime(new Date());
        return Response.success(this.updateById(infoBean));
    }

    /**
     * 删除
     */
    public Response deleteTemplate(String uuid) {
        MessageInfoEntity infoBean = this.getById(uuid);
        infoBean.setIsdelete("1");
        return Response.success(this.updateById(infoBean));
    }

    /**
     * 消息 已读 信息存表
     *
     * @param
     * @return
     */
    public void insertDisplayMessageWarning(MessageInfoVO messageInfoVO) {
        String userId = UserInfoUtil.getUserID();
        String uuid = messageInfoVO.getUuid();
        String updateTime = new SimpleDateFormat(CommonConstant.DATE_FORMAT_ONE).format(new Date());
        if (StringUtils.isNotEmpty(uuid) & StringUtils.isNotEmpty(userId)) {
            baseMapper.insertMessageUsersState(uuid, userId, updateTime);
        }
    }

    /**
     * 消息（已读、未读）内容及用户查询
     *
     * @param
     * @return
     */
    public Response<HashMap<String, Object>> queryReadMessageWarning(MessageInfoVO messageInfoVO) {
        //公司代码  测试
        List<String> companyList = new ArrayList<>();
        companyList.add("1");
        companyList.add("2");
        String userId = "111";
        //String userId = UserInfoUtil.getUserID();
        Integer state = messageInfoVO.getState();
        Integer pageSize = messageInfoVO.getPageSize();
        Integer currentPage = (messageInfoVO.getCurrentPage() - 1) * pageSize;

        List<MessageUsersStateEntity> messageUsersStateEntities = baseMapper.queryReadMessageWarning(companyList, currentPage,pageSize);
        List<MessageUsersStateVO> messageUsersStateVOList = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        List<MessageUsersStateVO> collect = null;
        for (MessageUsersStateEntity messageUsersStateEntity : messageUsersStateEntities) {
            MessageUsersStateVO messageUsersStateVO = new MessageUsersStateVO();
            BeanUtil.copyProperties(messageUsersStateEntity, messageUsersStateVO);
            messageUsersStateVO.setUserId(userId);
            if (queryMessageReadState(messageUsersStateEntity.getUuid())) {
                //已读消息装载
                messageUsersStateVO.setState(1);
            } else {
                //未读消息装载
                messageUsersStateVO.setState(0);
            }
            messageUsersStateVOList.add(messageUsersStateVO);
        }
        if (state == null) {
            collect = messageUsersStateVOList;
        } else {
            if (state == 0) {
                collect = messageUsersStateVOList.stream().filter(i -> 0 == i.getState()).collect(Collectors.toList());
            } else if (state == 1) {
                collect = messageUsersStateVOList.stream().filter(i -> 1 == i.getState()).collect(Collectors.toList());
            }
        }
        String countNoRed = baseMapper.querycountNoRed(companyList,userId);

        map.put("collect", collect);

        //未读条数统计
        map.put("countNoRed", countNoRed);
        //有未读消息：false  没有未读消息：true
        map.put("redPoint", "0".equals(countNoRed));
        return Response.success(map);
    }

    /**
     * 查询消息是否已读
     *
     * @param uuid
     */
    private boolean queryMessageReadState(String uuid) {

        List<String> userIds = baseMapper.queryMessageReadState(uuid);

        for (String userId : userIds) {
            if (userId.equals("111")) {
                return true;
            }
            ;
        }
        return false;
    }

}